﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Caching;
using Castle.MonoRail.Framework;
using StateTheater.Models;
using StateTheaterDataModel;

namespace StateTheater.Controllers
{
    public class QuoteItem : IQuote
    {
        #region IQuote Members
        public string Speaker { get; set; }
        public string Quote { get; set; }
        #endregion
    }
    public class QuoteComponent : ViewComponent
    {
		public Random RNG { get; set; }
		public StateTheaterDataContext Db{ get; set; }

        private List<QuoteItem> _quoteList = null;

        public override void Render()
        {
            QuoteItem item = NewQuote();
            PropertyBag["Speaker"] = item.Speaker;
            PropertyBag["QuoteText"] = item.Quote;
            Context.RenderBody();
            base.Render();
        }

        private QuoteItem NewQuote()
        {
            int skip = RNG.Next(this.QuoteList.Count);
            return QuoteList[skip];
        }

        private List<QuoteItem> QuoteList
        {
            get
            {
                ICacheProvider cacheProvider = this.EngineContext.Services.CacheProvider;
                if (_quoteList == null)
                {
                    _quoteList = cacheProvider.Get("quotelist") as List<QuoteItem>;
                }

                if (_quoteList == null)
                {
                    _quoteList = (from qu in Db.Quotes
                    select new QuoteItem 
                           {
                               Speaker = qu.Speaker,
                               Quote = qu.Quote1
                           }).ToList();

                    cacheProvider.Store("quotelist", _quoteList);
                }

                return _quoteList ?? new List<QuoteItem>();
            }
        }
    }
}
